import imgs from '../config/image'
import code from '../config/code'
import apis from '../config/api/index'
import message from './message'
import env from '../config/env'
import * as commonMethods from './commonReq'

/**
 * 获取当前项目信息同步版本
 */
async function getCurrentProjectSync() {
	let res = await apis.home.getCurrentProject();
	if (res.code == code.SUCCESS) {
		uni.setStorageSync('cisdiCurrentProject', res.data.currentProject);
		if (res.data.accessToken || res.data.refreshToken) {
			uni.setStorageSync('cisdiAccessToken', res.data.accessToken);
			uni.setStorageSync('cisdiRefreshToken', res.data.refreshToken);
		}
		getWorkbench();
	} else {
		uni.showModal({
			title: '温馨提示',
			content: `获取项目信息失败，错误码：${res.code},错误信息：${res.msg}`,
			showCancel: false,
			success: (action) => {
				if (action.confirm) {
					uni.removeStorageSync('cisdiAccessToken');
					uni.removeStorageSync('cisdiRefreshToken');
					uni.navigateBack();
				}
			}
		})
		return;
	}
}

/**
 * 获取当前项目信息异步版本
 */
function getCurrentProject() {
	apis.home.getCurrentProject().then(
		(res) => {
			uni.setStorageSync('cisdiCurrentProject', res.data.currentProject);
			if (res.data.accessToken || res.data.refreshToken) {
				uni.setStorageSync('cisdiAccessToken', res.data.accessToken);
				uni.setStorageSync('cisdiRefreshToken', res.data.refreshToken);
			}
			getWorkbench();
		},
		(err) => {
			uni.showModal({
				title: '温馨提示',
				content: `获取项目信息失败，错误码：${err.code},错误信息：${err.msg}`,
				showCancel: false,
				success: (res) => {
					if (res.confirm) {
						uni.removeStorageSync('cisdiAccessToken');
						uni.removeStorageSync('cisdiRefreshToken');
						uni.navigateBack();
					}
				}
			})
			return;
		}
	);
}

/**
 * 获取工作台
 */
function getWorkbench() {
	apis.home.getWorkbench().then((res) => {
		let appList = res.data?.apps ?? [];
		let cisdiOpearList = [];
		for (let item of appList) {
			cisdiOpearList.push(...(item.opts || []));
		}
		uni.setStorageSync('cisdiOpearList', cisdiOpearList);
	}, err => {
		uni.showModal({
			title: '温馨提示',
			content: `获取权限失败，错误码：${err.code},错误信息：${err.msg}`,
			showCancel: false,
			success: (res) => {
				if (res.confirm) {
					uni.removeStorageSync('cisdiAccessToken');
					uni.removeStorageSync('cisdiRefreshToken');
					uni.navigateBack();
				}
			}
		})
		return;
	});
}


export const common = {
	init: async () => {
		if (!uni.getStorageSync('cisdiHwConfig')) {
			await commonMethods.getOBSConfig();
		}
		getCurrentProject();
	},
	apis: {
		...apis
	},
	imgs,
	//公共消息
	message: {
		...message
	},
	commonMethods: {
		...commonMethods
	}
}